package com.ruoyi.common.utils.tool;

import org.apache.commons.codec.digest.DigestUtils;

import java.security.MessageDigest;
import java.util.*;

public class WechatPayUtil {

    public static String generateSign(Map<String, String> params, String key) {
        StringBuilder sb = new StringBuilder();
        Map<String, String> sortedParams = new TreeMap<>(params);
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.append("key=").append(key);

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(sb.toString().getBytes());
            StringBuilder sbSign = new StringBuilder();
            for (byte b : digest) {
                sbSign.append(String.format("%02x", b));
            }
            return sbSign.toString().toUpperCase();
        } catch (Exception e) {
            throw new RuntimeException("签名生成失败", e);
        }
    }
}